import plugin from '../../../lib/plugins/plugin.js'
import { Config } from '../components/index.js'
import { common } from '../model/index.js'
export class xyblack extends plugin {
  constructor() {
    super({
      name: '小月黑名单',
      dsc: '拉黑幸运儿',
      event: 'message',
      priority: 4999,
      rule: [
        {
          reg: '^#?新增(黑|白|保护)名单',
          fnc: 'ban',
        },
        {
          reg: '^#?移除(黑|白|保护)名单',
          fnc: 'remove',
        },
        {
          reg: '^#?查看(黑|白|保护)名单$',
          fnc: 'showban',
        },
      ]
    })
  }
  async ban(e) {
    if (!e.isMaster) return false
    if (e.msg.includes('保护')) {
      if (!e.isMaster && !e.member.is_owner) return false
    }
    let qq = e.at ?? e.msg.match(/\d+/)?.[0]
    if (!qq) return e.reply('未在消息内找到QQ号')
    let { value , key , list } = await init(e)
    if (value.includes(Number(qq))) return e.reply(`${list}上已有此人`)
    if (list !== '保护名单') {
    if (!await checkMember(Number(qq))) return e.reply(`${list == '黑名单' ? '白名单': '黑名单'}上已有此人，黑白名单不能共有此人`)
    }
    value.push(Number(qq))
    Config.modify('xyqg', key, value)
    e.reply(`用户${qq}添加成功`)
  }
  async remove(e) {
    if (!e.isMaster) return false
    if (e.msg.includes('保护')) {
      if (!e.isMaster && !e.member.is_owner) return false
    }
    let qq = e.at ?? e.msg.match(/\d+/)?.[0]
    if (!qq) return e.reply('未在消息内找到QQ号')
    let { value , key , list } = await init(e)
    if (!value.includes(Number(qq))) return e.reply(`${list}上未有此人`)
    value.splice(value.indexOf(Number(qq)), 1)
    Config.modify('xyqg', key, value)
    e.reply(`用户${qq}移除成功`)
  }

  async showban(e) {
    if (!e.isMaster) return false
    let { value , list } = await init(e)
    if (!value.length) return e.reply(`${list}上暂未有幸运儿~`)
    let msg = [`${list}上共有${value.length}个幸运儿`]
    for (let i = 0; i < value.length; i++) {
          msg.push(`${i+1}.${value[i]}`)
    }
    common.getforwardMsg(e, msg, list, 0, false, true)
  }
}

async function init(e) {
  let config = await Config.xyqg
  let value
  let key
  let list
  if (e.msg.includes('黑')) {
    value = config.blackList
    key = 'blackList'
    list = '黑名单'
  } else if (e.msg.includes('白')) {
    value = config.whileList
    key = 'whileList'
    list = '白名单'
  } else {
    value = config.proList
    key = 'proList'
    list = '保护名单'
  }

  return { value, key, list }
}

async function checkMember(qq) {
  let config = await Config.xyqg
  if (config.blackList.includes(qq) || config.whileList.includes(qq)) return false
  return true
}